package com.leyou.gateway.filters;

import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.task.AppTokenHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class PrivilegeFilter implements GlobalFilter, Ordered {

    @Autowired
    private AppTokenHolder appTokenHolder; //定时任务拿取token
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取token
        String token = appTokenHolder.getToken();
        //添加请求头
        ServerHttpRequest host = exchange.getRequest().mutate().header(
                jwtProperties.getApp().getHeaderName(), token).build();
        ServerWebExchange build = exchange.mutate().request(host).build();

        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return 6;
    }
}
